<template>
	<a-card v-if="props.viewType === 'record'">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="主叫号码" name="caller">
						<a-input v-model:value="searchFormState.caller" placeholder="请输入主叫号码" enter-button allowClear />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="被叫号码" name="callee">
						<a-input v-model:value="searchFormState.callee" placeholder="请输入被叫号码" enter-button allowClear />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="坐席账号" name="userName">
						<a-input v-model:value="searchFormState.userName" placeholder="请输入坐席账号" enter-button allowClear />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="任务ID" name="taskId">
						<a-input v-model:value="searchFormState.taskId" placeholder="请输入任务ID" enter-button allowClear />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="通话时长" name="callDuration">
						<a-input
							v-model:value="searchFormState.callDuration"
							placeholder="请输入通话时长"
							enter-button
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="回传时间">
						<a-range-picker
							v-model:value="createTimeArr"
							@change="dateChange"
							:default-value="[dayjs('2024-11-11', 'YYYY-MM-DD'), dayjs('2024-11-15', 'YYYY-MM-DD')]"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="通话类型" name="callType">
						<a-select
							v-model:value="searchFormState.callType"
							placeholder="请选择通话类型"
							:options="callTypeOptions"
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="呼叫序列号" name="callDuration">
						<a-input v-model:value="searchFormState.callId" placeholder="请输入呼叫序列号" enter-button allowClear />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="所属公司" name="deptId">
						<a-tree-select
							v-model:value="searchFormState.deptId"
							class="xn-wd"
							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
							placeholder="请选择组织"
							allow-clear
							tree-default-expand-all
							:tree-data="treeData"
							:tree-default-expanded-keys="treeDefaultExpandedKeys"
							:field-names="{
								children: 'children',
								label: 'name',
								value: 'id'
							}"
						></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="tableRef.refresh(true)">查询</a-button>
					<!--					<a-button type="primary" @click="sendMessage">发送</a-button>-->
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card>
		<s-table
			ref="tableRef"
			:size="pageOptions.size"
			:pageSizeOptions="pageOptions.sizeOptions"
			:columns="columns"
			:data="loadData"
			:row-key="(record) => record.id"
			:scroll="{ x: 'max-content' }"
		>
			<template #asrName="{ text }">
				<span v-if="text === '识别失败'">无彩铃</span>
				<span v-else>{{ text }}</span>
			</template>
			<template #signal="{ text }">
				<span v-if="text === 2">是</span>
				<span v-else>否</span>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'fileUrl' && record.fileUrl != null && record.fileUrl !== ''">
					<a-space>
						<a-button type="link" size="small" @click="toCall(record)">播放</a-button>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<xn-form-container title="录音播放" :width="1000" :visible="visible" :destroy-on-close="true" @close="onClose">
		<Audio :audioUrl="audioUrl" :isStop="isStop" />
		<!-- 仿微信聊天记录 -->
		<ChatWindow :current-user="currentUser" :target-user="targetUser" :messages="messages" />
	</xn-form-container>
</template>

<script setup name="Record">
	import htApi from '@/api/tjzy/call/ht/htApi'
	import Audio from '@/components/AudioView/index.vue'
	import dayjs from 'dayjs'
	import tool from '@/utils/tool'
	import bizUserApi from '@/api/biz/bizUserApi'
	//仿微信聊天记录
	import { ref } from 'vue'
	import ChatWindow from '@/views/qc/voice/chat/ChatWindow.vue'
	import voiceTextApi from '@/api/qc/voice/text/voiceTextApi'

	// 在父组件中调用示例
	const messageListRef = ref(null)

	// 模拟数据
	const currentUser = reactive({
		id: 1,
		name: '客服',
		avatar: new URL('@/assets/images/service_avatar.png', import.meta.url).href
	})

	const targetUser = reactive({
		id: 2,
		name: '客户',
		avatar: new URL('@/assets/images/customer_avatar.png', import.meta.url).href
	})

	const messages = ref([])
	const callId = ref()

	const callTypeOptions = tool.dictList('TalkType')

	const props = defineProps({
		viewType: String,
		caseId: String
	})
	const searchFormRef = ref()
	const searchFormState = ref({
		current: 1,
		size: 5,
		caseId: props.caseId,
		caller: undefined,
		callee: undefined,
		userName: undefined,
		taskId: undefined,
		callDuration: undefined,
		beginTime: props.viewType === 'record' ? dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss') : undefined,
		endTime: props.viewType === 'record' ? dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss') : undefined,
		deptId: undefined
	})
	const treeData = ref([])
	const treeDefaultExpandedKeys = ref([])
	const tableRef = ref()
	const columns = [
		{
			title: '通话类型',
			dataIndex: 'callTypeName'
		},
		{
			title: '呼叫序列号',
			dataIndex: 'callId'
		},
		{
			title: '主叫',
			dataIndex: 'caller'
		},
		{
			title: '被叫',
			dataIndex: 'callee'
		},
		{
			title: '任务ID',
			dataIndex: 'taskId'
		},
		{
			title: '彩铃识别',
			dataIndex: 'asrName',
			slots: { customRender: 'asrName' }
		},
		{
			title: '坐席',
			dataIndex: 'agentNum'
		},
		{
			title: '通话开始时间',
			dataIndex: 'startTime'
		},
		{
			title: '通话结束时间',
			dataIndex: 'endTime'
		},
		{
			title: '通话时长',
			dataIndex: 'callDuration'
		},
		{
			title: '号码归属地',
			dataIndex: 'area'
		},
		{
			title: '呼叫结果',
			dataIndex: 'result'
		},
		{
			title: '是否坐席挂断',
			dataIndex: 'signal',
			slots: { customRender: 'signal' }
		},
		{
			title: '话单回传时间',
			dataIndex: 'createdTime'
		},
		{
			title: '通话录音',
			dataIndex: 'fileUrl',
			fixed: 'right',
			align: 'center'
		}
	]
	const visible = ref(false)
	const audioUrl = ref('')
	const isStop = ref(false)
	const createTimeArr = ref([dayjs().startOf('day'), dayjs().endOf('day')])
	const pageOptions = {
		size: props.viewType === 'record' ? 10 : 5,
		sizeOptions: props.viewType === 'record' ? [] : ['5', '10', '20']
	}
	const loadData = (parameter) => {
		searchFormState.value.current = parameter.current
		searchFormState.value.size = parameter.size
		return htApi.callRecordPage(searchFormState.value).then((res) => {
			console.log(res)
			return res
		})
	}
	const toCall = (record) => {
		visible.value = true
		audioUrl.value = record.fileUrl
		//获取通话内容文本
		// console.log('播放的记录是 -> ',record);
		//查询语音文本
		voiceTextApi.getTextByCallId(record.callId).then((res) => {
			//原来的聊天记录
			// messageList.value = res;
			//仿微信聊天记录
			messages.value = []
			//把res转化成messages
			res.forEach((item) => {
				console.log('聊天内容 -> ', item)
				messages.value.push({
					id: item.id,
					content: item.content,
					timestamp: item.chatTime,
					isSelf: item.speakerRole === 2
				})
			})
		})
	}
	const onClose = () => {
		visible.value = false
		isStop.value = true
		setTimeout(() => {
			isStop.value = false
		}, 500)
	}
	const dateChange = (value) => {
		searchFormState.value.beginTime = value[0].format('YYYY-MM-DD').concat(' 00:00:00')
		searchFormState.value.endTime = value[1].format('YYYY-MM-DD').concat(' 23:59:59')
	}
	const reset = () => {
		searchFormRef.value.resetFields()
		createTimeArr.value = [dayjs().startOf('day'), dayjs().endOf('day')]
		searchFormState.value.beginTime = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss')
		searchFormState.value.endTime = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
		// htApi.syncCallRecord()
	}
	const sendMessage = () => {
		htApi.sendMessage()
	}
	onMounted(() => {
		bizUserApi.userOrgTreeSelector().then((res) => {
			if (res !== null) {
				treeData.value = res
				// 默认展开2级
				treeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === '0') {
						treeDefaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								treeDefaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
			}
		})
	})
</script>
